<?php

namespace app\admin\controller\crm;

use app\admin\controller\BaseController;
use app\admin\logic\crm\CustomersLogic;
use support\Request;
use support\Response;

/**
 * 合作企业控制器
 */
class CustomersController extends BaseController
{
    /**
     * 构造
     */
    public function __construct()
    {
        $this->logic = new CustomersLogic();
        parent::__construct();
    }

    /**
     * 数据列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request) : Response
    {
        $where = $request->more([
            ['page', 1],
            ['limit', 20],
            ['name', ''],
            ['user', ''],
            ['brands', ''],
            ['phone', ''],
            ['contact_person', ''],
            ['area_id', 0],
            ['stage', 0],
            ['user_tags', []],
            ['create_time', []],
            ['user_id', $this->user['id'] ?? 0],
        ]);
        $data = $this->logic->getCustomerList($where);
        return $this->success($data);
    }

    /**
     * 获取客户详情
     * @param Request $request
     * @return Response
     */
    public function read(Request $request, $id) : Response
    {
        if (!$id) {
            return $this->fail('客户ID不能为空');
        }
        $scene = $request->input('scene', '');
        $customer = $this->logic->getCustomerDetail($id, $scene);
        if (!$customer) {
            return $this->fail('客户不存在');
        }

        return $this->success($customer);
    }

    /**
     * 保存客户
     * @param Request $request
     * @return Response
     */
    public function save(Request $request) : Response
    {
        try {
            $data = $request->post();
            $result = $this->logic->saveCustomer($data);
            return $this->success($result, '保存成功');
        } catch (\Exception $e) {
            $error = $e->getMessage();
            // 处理JSON格式的字段验证错误
            if (strpos($error, '{') === 0) {
                $errors = json_decode($error, true);
                if (is_array($errors)) {
                    return $this->fail('字段验证失败', $errors);
                }
            }
            return $this->fail($error);
        }
    }

    /**
     * 更新客户
     * @param Request $request
     * @return Response
     */
    public function update(Request $request, $id) : Response
    {
        if (!$id) {
            return $this->fail('客户ID不能为空');
        }

        try {
            $data = $request->post();
            
            $result = $this->logic->updateCustomer($id, $data);
            return $this->success($result, '更新成功');
        } catch (\Exception $e) {
            $error = $e->getMessage();
            // 处理JSON格式的字段验证错误
            if (strpos($error, '{') === 0) {
                $errors = json_decode($error, true);
                if (is_array($errors)) {
                    return $this->fail('字段验证失败', $errors);
                }
            }
            return $this->fail($error);
        }
    }

    /**
     * 删除客户
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request, $id) : Response
    {
        if (!$id) {
            return $this->fail('客户ID不能为空');
        }

        $result = $this->logic->deleteCustomer($id);
        if ($result) {
            return $this->success([], '删除成功');
        }
        return $this->fail('删除失败');
    }
    
    /**
     * 分配负责人
     * @param Request $request
     * @return Response
     */
    public function assignManager(Request $request)
    {
        $customerId = $request->input('customer_id');
        $userId = $request->input('user_id');
        if (empty($customerId)) {
            return $this->fail('客户ID不能为空');
        }
        if (empty($userId)) {
            return $this->fail('负责人不能为空');
        }
        $result = $this->logic->assignManager($customerId, $userId);
        if ($result === true) {
            return $this->success([], '分配成功');
        }
        return $this->fail($result ?? '分配失败');
    }
    
    public function disabledCustomer(Request $request)
    {
        $customerId = $request->input('customer_id');
        if (empty($customerId)) {
            return $this->fail('客户ID不能为空');
        }
        $result = $this->logic->disabledCustomer($customerId);
        if ($result === true) {
            return $this->success([], '禁用成功');
        }
        return $this->fail($result ?? '禁用失败');
    }
    
    public function customerFollowups(Request $request) : Response
    {
        $id = $request->input('id', 0);
        if (!$id) {
            return $this->fail('客户ID不能为空');
        }
        $logs = $this->logic->getCustomerFollowUps($id);
        return $this->success($logs);
    }
    
    public function customerLogs(Request $request) : Response
    {
        $id = $request->input('id', 0);
        if (!$id) {
            return $this->fail('客户ID不能为空');
        }
        $logs = $this->logic->getCustomerLogs($id);
        return $this->success($logs);
    }
    
    public function customerAttachments(Request $request) : Response
    {
        $id = $request->input('id', 0);
        if (!$id) {
            return $this->fail('客户ID不能为空');
        }
        $attachments = $this->logic->getCustomerAttachments($id);
        return $this->success($attachments);
    }
    
    public function uploadAttachment(Request $request) : Response
    {
        $id = $request->input('id', 0);
        if (!$id) {
            return $this->fail('客户ID不能为空');
        }
        $file = $request->file('file');
        if (!$file) {
            return $this->fail('文件不能为空');
        }
        $result = $this->logic->uploadAttachment($id);
        if (!empty($result)) {
            return $this->success($result, '上传成功');
        }
        return $this->fail('上传失败');
    }
    
    public function deleteAttachment(Request $request) : Response
    {
        $id = $request->input('id', 0);
        if (!$id) {
            return $this->fail('附件ID不能为空');
        }
        $result = $this->logic->deleteAttachment($id);
        if ($result) {
            return $this->success([], '删除成功');
        }
        return $this->fail('删除失败');
    }
    
    public function export(Request $request) : Response
    {
        $where = $request->more([
            ['name', ''],
            ['user', ''],
            ['brands', ''],
            ['phone', ''],
            ['contact_person', ''],
            ['area_id', 0],
            ['stage', 0],
            ['user_tags', []],
            ['create_time', []],
            ['user_id', $this->user['id'] ?? 0],
        ]);
        
        return $this->logic->export($where);
    }
}
